// Raw IRC circapi.cpp example for use with circapi (circapi.sourceforge.net)
// this is similar to telnet, but ping responces are automated

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <errno.h>
#include <circapi.h>
#include <pthread.h>

unsigned char EXIT;

int irc_socket;

void *keyboard_input_loop(void *v)
{
	char *p;
	char buff[8192];
	
	p=buff;
	while(1)
	{
		sleep(1);
		
		// get input text
		if(EXIT >= 1)
		{
			return NULL;
		}
		
		memset(buff, '\0', sizeof(buff));
		p=buff;
		
		while((*p = getchar()) != EOF && *p != '\n')
		{
			++p;
		}
		
		*p = '\r';
		++p;
		*p = '\n';
		++p;
		*p = '\0';
		
		if(!strncmp(buff, "COMMAND FORCEQUIT", 17))
		{
			EXIT=1;
			return NULL;
		}
		else if(!strncmp(buff, "COMMAND QUIT", 12))
		{
			irc_send_server_text(&irc_socket, "quit :exited terminal\r\n");
			EXIT=1;
			return NULL;
		}
		else if(irc_send_server_text(&irc_socket, buff) <= 0)
		{
			fprintf(stderr, "Unable to send text, try again? [%s]\n", buff);
		}
	}
}

void *irc_input_loop(void *v)
{
	struct ircofs ofs;
	char buff[8192];
	int attempt, x;
	
	puts("Connecting...");
	for(attempt=0; attempt < 5
		&& (x=irc_connect(&irc_socket, ((char **)v)[1], ((char **)v)[2], ((char **)v)[3], "guest", 1, ((char **)v)[4], 0)) <= 0; ++attempt)
	{
		printf("Could not connect to %s:%s, trying again.\n", ((char **)v)[1], ((char **)v)[2]);
	}
		
	if(x <= 0) 
	{
		fputs("Unable to connect.", stderr);
		++EXIT;
		return NULL;
	}
	
	while(1)
	{
		sleep(1);
		memset(buff, '\0', sizeof(buff));
		if(EXIT == 1) return NULL;
		if(irc_get_server_text(&irc_socket, buff, sizeof(buff)) > 0)
		{
			printf(buff);
			irc_ircofs_init(&ofs);
			irc_buff2ircofs(&ofs, buff);
			for(x=0; x<ofs.line_ct; ++x)
			{
				if(irc_is_ping(ofs.ln[x]))
				{
					memset(buff, '\0', sizeof(buff));
					irc_ping_responce(ofs.ln[x], buff);
					if(irc_send_server_text(&irc_socket, buff) <= 0)
					{
						fputs("Warning: unable to send PING responce!", stderr);
					}
					else
					{
						puts("PING? PONG!");
					}
				}
			}
		}
	}
}

int main(int argc, char *argv[], char *env[])
{
	pthread_t kbl, ircl;
	int retval1, retval2;
	
	EXIT=0;
	if(argc <= 4)
	{
		printf("Useage:\n\n\t%s <server hostname> <server port> <nick> <real name>\n", argv[0]);
		return 0;
	}
	
	retval1 = pthread_create(&kbl, NULL, &keyboard_input_loop, (void *)argv);
	retval2 = pthread_create(&ircl, NULL, &irc_input_loop, (void *)argv);
	
	pthread_join(kbl, NULL);
	pthread_join(kbl, NULL);
	
	return 0;
}

